package com.woniuxy.sales.controller;

import com.woniuxy.sales.model.entity.Reviews;
import com.woniuxy.sales.model.entity.Users;
import com.woniuxy.sales.model.vo.ReviewsVo;
import com.woniuxy.sales.service.ReviewsService;
import com.woniuxy.sales.untils.JwtTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/reviews")
@Api(tags = "评论接口")
@Slf4j
public class ReviewsController {

    @Autowired
    private ReviewsService reviewsService;
    @Autowired
    private JwtTemplate jwtTemplate;

    @GetMapping("/query")
    @ApiOperation("查询评论")
    public ResponseEntity query(@RequestHeader(name = "Authorization", required = false) String token) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        log.info("用户id:{}", userId);
        //调用业务层查询订单
        List<ReviewsVo> reviewsVos = reviewsService.query(userId);
        log.info("所有评论信息:{}", reviewsVos);
        return ResponseEntity.ok(reviewsVos);
    }


    @DeleteMapping("/remove/{id}")
    @ApiOperation("删除评论")
    public ResponseEntity remove(@PathVariable Integer id) {
        //调用业务层创建订单
        reviewsService.remove(id);
        return ResponseEntity.ok().build();
    }


    @PostMapping("/submit")
    @ApiOperation("提交评论")
    public ResponseEntity<?> submitReview(@RequestHeader(name = "Authorization", required = false) String token,
                                          @RequestBody Reviews reviews) {
        // 从 token 获取用户ID
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));

        // 乘以2来调整评分范围
        reviews.setRating(reviews.getRating() * 2);

        // 调用 Service 层提交评论
        reviewsService.submitReview(reviews, userId);

        return ResponseEntity.ok().build();
    }

    @GetMapping("/getReviewsByCarId")
    @ApiOperation("根据id查询评论")
    public ResponseEntity<List<Reviews>> getReviewsByCarId(@RequestParam Integer carId) {
        List<Reviews> reviews = reviewsService.getReviewsByCarId(carId);
        return ResponseEntity.ok(reviews);
    }


    @GetMapping("/getReviewsByUserId")
    @ApiOperation("根据多个userId查询用户名")
    public ResponseEntity<List<Users>> getReviewsByUserId(@RequestParam Integer userId) {
        List<Users> username = reviewsService.getReviewsByUserId(userId);
        return ResponseEntity.ok(username);
    }







}